<?   
define ('WRITE', 'w');   
define ('READ', 'r');    
define ('APPEND', 'a');                   
$multi_test = NULL;       
$log=array();               
if ($action=="eview")                      
{                      
    $body = $nntp->get_body_only($m);                      
    if (preg_match("/^begin\s+\d{3}\s+(.*)$/im", $body, $header))                      
    {                      
        $body = str_replace($header[0], "", $body);                      
    }                      
    header("Content-Type: video/mpeg");                      
    uudecode_output  (trim($body));                        
    exit;                      
}               
else if ($action=="build")                      
{               
	if ($_GET['x']=="db")                      
	{                  
//		$a=array(); 
//        $enc  = new yenc();  
//		$n[]='data/temp/5939934_tmp.log.ntx___.txt'; 
//		$n[]='data/temp/5939973_tmp.log.ntx___.txt'; 
//		$n[]='data/temp/5939981_tmp.log.ntx___.txt'; 
//		$n[]='data/temp/5939987_tmp.log.ntx___.txt';   
//		foreach ($n as $n1)
//		{
//			$fx=fopen ($n1, READ);            
//			$am=fread($fx, filesize($n1));        
//			fclose ($fx);
//			$i=$enc->getinfo ($am);
//			echo '<xmp>';	
//			print_r ($i);
//			echo '</xmp>';	
//		}	
		
		                                       
            # pull the article body here                                             
            if (! $MIME_Message = $nntp->get_article($m))                                             
            { # throw an error if the article body is not found                                             
                $breadcrumb .= "Unable to read message [$m] on [$nntp_server] in [$group]";                                             
                echo $breacrumb;                     
                exit;                                             
            }                                                
                                                         
            $nntp->quit();    // Quit sooner to release the resources                                                 
                                                         
                                                         
            $header = $MIME_Message->get_main_header();                                               
            $parts  = $MIME_Message->get_all_parts();              
		
		echo '<xmp>';	
		print_r ($header );
		print_r ($parts );
		echo '</xmp>';	
		
		exit;
	} 
	
    $decode           = $_GET["decode"];                      
    $pointer          = $_GET["pointer"];                      
    $decode_on_server = strlen($decode) > 0;                      
    $file_name        = CACHE_PATH . $m . "_tmp.log";                       
    $pointer_name     = CACHE_PATH . "pointer/" . base64_encode ($m);          

							   
	if (! $MIME_Message = $nntp->get_article($m))                                             
	{ # throw an error if the article body is not found                                             
		$breadcrumb .= "Unable to read message [$m] on [$nntp_server] in [$group]";                                             
		echo $breacrumb;                     
		exit;                                             
	}                                                
	$parts  = $MIME_Message->get_all_parts();      
	$body   = NULL;
	foreach ($parts as $part)      
		$body = $part['body'];		
                  
    if ($body/* = $nntp->get_body_only($m)*/)                      
    {                       
         #$ftmp=fopen ($file_name."_debugger.txt",WRITE);                      
         #fwrite ($ftmp, $body);                      
         #fclose ($ftmp);                      
        $log[] = 'retrieved body for '.$m;                        
        if ($decode_on_server)                      
        {       
            $log[] = 'decode_on_server for '.$m;                 
			$wait = strlen($body);               
            $body = body_render ($body, $action, true, $_GET["force"]);        
            $type = $body["type"];                      
            $name = $body["name"];                      
            $body = $body["body"];                      
            $ext  = "";                      
        }                      
        else                      
        {               
            $log[] = 'checking file type for '.$m;    
			$headersize = 0;       
			$fname      = '';    
            if (preg_match("/^=ybegin.*name=([^\\r\\n]+)/im", $body, $header))                      
            {                      
                $ext   = ".ntx";                      
                $type  = "text/yenc";    
				$fname = $header[1];          
				preg_match("/^=ybegin.*size=([^ $]+)/im", $encoded, $header);   
				$headersize = $header[1];            
            }                      
            else                      
            {                 
				if (preg_match ('/begin\s+(\d+)\s+(.*)/im', $body, $header))
				    $fname = $header[2];                      
                $ext  = ".uue";                      
                $type = "text/uuencoded";                       
            }    
			
            $log[] = 'type is '.$type;  
		
			if (strlen(trim($body)) > 0)
			{                 
            	$log[] = 'saving '.$file_name.$ext;     
				$fp=fopen ($file_name.$ext, WRITE);                      
				fwrite ($fp,$body);                      
				fclose ($fp);   
				$reported_name = str_replace('#','',$fname);
				$reported_size = filesize($file_name.$ext); 
				   
				echo '=download name=' . $reported_name . ' size=' . $reported_size . ' total=' . $headersize . ' type=' . $type . '';  
				exit;              
				#print str_replace('#','',$fname) . "(".filesize($file_name.$ext).") cached!" . $type . "!" . $nntp_server;                      
			}
			else
			{
				echo 'ERROR: no body in file ['.$m.']' ;
			}  
			echo implode ("<br>\n", $log);
            exit;                      
        }                      
                                
        if ($_GET["saveas"]!="")                      
        { # rename the file to its final name                      
            $save_name = CACHE_PATH . stripslashes($_GET["saveas"]);                      
            rename($file_name, $save_name . $ext);                      
            $file_name = $save_name;              
            $pointer = $_GET["saveas"];                  
            $act = "saved!";                
            $log[] = '1. renaming '.$file_name.' to '.$save_name . $ext;            
        }                      
        else if ($_GET["parent"]=="")                      
        { # save the very first segment of the file                      
            $act = "saved";                      
            $fp=fopen ($file_name, WRITE);   
            if ($name!="")  
            {  
                $pointer = $name;  
            }     
            $log[] = 'opening '.$file_name;                   
        }                       
        else                      
        { # append to the file as it is being built                      
            $file_name = CACHE_PATH . $_GET["parent"] . "_tmp.log";                       
            $act = "updated";                      
            $fp=fopen ($file_name, APPEND);      
            $log[] = 'updating '.$file_name;                               
        }                        
        if ($pointer!="")                      
        { # save a pointer file to this file          
            $fx=fopen ($pointer_name, WRITE);            
            fwrite ($fx, $pointer);                      
            fclose ($fx);        
            $log[] = 'saving useless pointer '.$pointer_name;          
        }     
		if (strlen(trim($body)) > 0)
		{             
        	fwrite ($fp, $body); 
            echo str_replace('#','',$file_name) . " (".filesize($file_name).") ".$act."!" . $type . "!" . $nntp_server . "#" . $name . "#" . $wait;    
            $log[] = 'saving '.$file_name;              
		}
		else
		{
			echo 'ERROR: no body in file ['.$m.']' ;
		}                                     
        fclose ($fp);                                        
    }                      
    else if ($_GET["saveas"]!="")                      
    {                       
        $save_name = CACHE_PATH . $_GET["saveas"];                      
        rename($file_name, $save_name . $ext);                      
        $file_name = $save_name;                       
        $act = "saved!";    
        $log[] = '2. renaming '.$file_name.' to '.$save_name . $ext;                        
    }                      
    else                      
    {                      
        echo "ERROR: " . $m . " could not be found on " . $nntp_server . "!\n";                      
        echo $nntp->get_error_message() . "!\n";                      
        echo get_request ("art_group");                      
    }   
     echo implode ("<br>\n", $log);                      
    exit;                      
}                      
else if ($action=="decode")                      
{                        
    $type = $_GET["force"];                     
    $open = $_GET["openas"];                     
    if ($type == "text/yenc")                      
    {                         
        $ext  = ".ntx";                     
        $force = "yenc";                     
    }                      
    else if ($type == "text/uuencoded")                      
    {                      
        $ext  = ".uue";                       
        $force = "uudecode";                     
    }                       

    $save_name = CACHE_PATH . $_GET["saveas"];                     
//    if (strpos ($m,',')!==false)
//	{
//		$am = explode (',',$m);
//		$fe = array ();
//		foreach ($am as $m)
//		{
//			$file_name = CACHE_PATH . $m . "_tmp.log" . $ext;                      
//			
//			$fp=fopen ($file_name, READ);                     
//			$fe[]=trim(fread ($fp,filesize($file_name)));                     
//			fclose ($fr);                     
//			unlink ($file_name);    
//			
//		}   	
//				   
//		$body = body_render ($fe, $action, true, $force);                     
//		$fp=fopen ($save_name, WRITE);                      
//		fwrite ($fp,$body["body"]);                      
//		fclose ($fp);             
//						 
//		print $save_name .  " (" . sizeof ($am) . " parts) --> $ext (".filesize($save_name).") saved!" . $type . "!" . $nntp_server;                      
//		exit;              
//	}
	
	
	$file_name = CACHE_PATH . $m . "_tmp.log" . $ext;                      
    if (!file_exists ($file_name))
	{
		echo $file_name . ' does not exist!';
		exit;
	}
	
	$fp=fopen ($file_name, READ);                     
    $fr=fread ($fp,filesize($file_name));                     
    fclose ($fr);                     
    unlink ($file_name);    
    #rename ($file_name,$file_name.'___.txt');    
	               
    $body = body_render ($fr, $action, true, $force); 
	
	if (strlen($body["body"])==0)
	{
		echo 'ERROR: no body in ' . $file_name;
     	echo implode ("<br>\n", $log);   
		exit;
	}
	                    
    $fp=fopen ($save_name, $open);                      
    fwrite ($fp,$body["body"]);                      
    fclose ($fp);      
	  
//    $fp=fopen ($file_name.'____debug____' . time() . '.txt', WRITE);                      
//    fwrite ($fp,$body["body"]);                      
//    fclose ($fp);      
	
	                
    print str_replace('#','',$save_name) .  " $ext (".filesize($save_name).") saved!" . $type . "!" . $action.'::'.$force;      
     echo implode ("<br>\n", $log);                   
    exit;                     
//                       
//                          
//                          
//    $body  = $nntp->get_body_only($m);                         
//                           
//                           
//    #$type = "none";                      
//                          
//    if ($_GET["saveas"]!="")                      
//    {                       
//        $save_name = CACHE_PATH . $_GET["saveas"];                      
//        rename($file_name, $save_name . $ext);                      
//        $file_name = $save_name;                       
//        $act = "saved!";                       
//    }                       
//    else                      
//    {                      
//        $fp=fopen ($file_name, READ);                      
//        $body = fread($fp, filesize($file_name));                      
//        $body = body_render ($body, $action, true, $_GET["force"]);                       
//                            
//        $act = "updated";                      
//        $fp=fopen ($file_name, APPEND);                      
//    }                      
//    fwrite ($fp, $body);                      
//    fclose ($fp);                      
//    print $file_name . " (".filesize($file_name).") ".$act."!" . $type . "!" . $nntp_server;                      
//    exit;                      
}                      
else if ($action=="save")                      
{                       
    $save_name = CACHE_PATH . $_GET["saveas"];                       
    $body  = $nntp->get_body_only($m);                        
    $body = body_render ($body, $action, true);                       
    $body = $body["body"];                      
                           
    $fp=fopen ($save_name, WRITE);                      
    fwrite ($fp, $body);                      
    fclose ($fp);                      
    print $save_name . " saved!";                          
                          
    exit;                      
}                      
else if ($action=="nview")                      
{                      
    $MIME_Message = $nntp->get_header($m);                      
    $header = $MIME_Message->get_main_header();                        
    $multi_test = multipart_lookup ($header["subject"], $nntp);                        
    if (count($multi_test["sorter"])>0)                      
    {                        
        $s=$multi_test["sorter"][0];                      
        $m=$multi_test["matches"][$s]->nntp_message_id;                      
        $body = $nntp->get_body_only($m);                       
    }                      
}                      
else                      
{                      
    $body = $nntp->get_body_only($m);                      
}                       




function body_render ($body, $action, $return=false, $force=false)                      
{                      
    $execution_end_index = time();                      
    $execution_span      = $execution_end_index-$execution_start_index;                      
    $maxsize             = 500;                      
    $loadedbits          = 0;  
	 global $log;
	if (!is_array($body))
	{
		if (strlen(trim($body))==0)
		{
			echo "Error: The $force file is corrupt or did not download properly.";
		}   
	}   
	              
    if ( ($force=="yenc") || (strpos($body, "ybegin") !== false) || (strpos(strtolower($subject), "yenc") !== false) )                      
    { // YENC decoding                      
        
		$ping = is_array($body) ? $body[0] : $body;
		                  
        preg_match("/^=ybegin.*name=([^\\r\\n]+)/im", $ping, $header);                       
        $filename = trim($header[1]);                       
                                
		preg_match("/^=yend.*size=([^ $\\r\\n]+)/im", $ping, $trailer);  
		$trailersize = trim($trailer[1]);   
		
		if ($trailersize=="")
		{
		    echo "Error: Trailer size is not present. The yEnc file is corrupt or did not download properly.";
		} 
        // Extract the yEnc string itself.                                           
        if ($cookie=="raw")                      
        {                       
            $body = trim($ping);                      
        }                      
        else                      
        {                      
            $enc  = new yenc();                       
            $body = $enc->decode( $body, "", false );                         
            $enc = null;                      
        }                        
                               
        $execution_yenc_index = time();                      
        $execution_yenc_span = $execution_yenc_index-$execution_end_index;                      
                               
        if ($action=="save")                      
        {                      
            header("Content-Type: yenc/encoded");                      
            header("Content-Name: " . $filename);                      
            header("Content-Span: " . $execution_span . "-" . $execution_yenc_span);                       
        }                        
        if ($return)                      
        {                      
            return array("body"=>$body, "type"=>"yenc", "name"=>$filename);                       
        }                      
        else                      
        {                      
            print $body;                       
        }                       
    }                        
    else if ( ($force=="uudecode") || preg_match("/^begin\s+\d{3}\s+(.*)$/im", $body, $header))                      
    {                      
		$log[]='got decoder ['.$action.'/'.$force.']';
		$log[]='body size is ['.strlen($body).']';
		 if (preg_match("/^begin\s+\d{3}\s+(.*)$/im", $body, $header))
		 {
             $body = str_replace($header[0], "", $body);   
		     $log[]='stripping '.strlen($header[0]).' bytes';  
		 }             
        $filename = trim($header[1]);                        
        if ($action=="save")                      
        {                      
            header("Content-Type: uuencoded");                      
            header("Content-Name: " . $filename);                      
            header("Content-Span: " . $execution_span);                       
        }                       
        else if ($force=="uudecode")                      
        {           
		    $log[]='decoding '.strlen($body).' bytes';           
            $body = uudecode (trim($body));                       
        }                       
        else                      
        {                      
		    $log[]='decoding and trimming '.strlen($body).' bytes';      
            $body = uudecode (trim($body));                         
        }   
		$log[]='body size is now ['.strlen($body).']';                     
        if ($return)                      
        {                       
            return array("body"=>$body, "type"=>"uudecode", "name"=>$filename);                       
        }                      
        else                      
        {                      
            print $body;                       
        }                        
    }                       
    else                      
    {                       
        if ($action=="save")                      
        {                      
             header("Content-Span: " . $execution_span);                        
        }                         
        if ($return)                      
        {                      
            return array("body"=>uudecode (trim($body)), "type"=>"uudecode", "name"=>"");                        
        }                      
        else                      
        {                      
            print $body;                       
        }                        
    }                         
}                      

body_render ($body, $action);                      
                        
$nntp->quit();                      
exit;                      
?>